﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace EF通用方法
{

    public class BaseDAL<T> where T : class
    {
        public int Add(T t)
        {
            using (var db = new BaseContext())
            {
                db.Set<T>().Add(t);
                return db.SaveChanges();
            }
        }

        public int Edit(T t)
        {
            using (var db = new BaseContext())
            {
                db.Set<T>().Attach(t);
                db.Entry(t).State = System.Data.Entity.EntityState.Modified;
                return db.SaveChanges();
            }
        }

        public List<T> GetList()
        {
            using (var db = new BaseContext())
            {
                return db.Set<T>().AsNoTracking().ToList();
            }
        }

        public List<T> GetWhereList(Expression<Func<T, bool>> WhereLamda)
        {
            using (var db = new BaseContext())
            {
                return db.Set<T>().Where(WhereLamda).ToList();
            }
        }

        public List<T> GetPageList<TKey>(Expression<Func<T, bool>> WhereLamda, Expression<Func<T, TKey>> OrderLamda, int PageIndex, int PageSize)
        {
            using (var db = new BaseContext())
            {
                return db.Set<T>().Where(WhereLamda)
                                  .OrderBy(OrderLamda)
                                  .Skip((PageIndex - 1) * PageSize)
                                  .Take(PageSize).ToList();
            }

        }
    }
}
